const express = require('express');
const goodsRouter = express.Router();
const goodsSer = require('../../services/goodsServe');

// 添加商品
goodsRouter.post('/add',async (req,res)=>{
    let {name,price,img,detailsImg,discount}=req.body;
    if(name==undefined||price==undefined||img==undefined) return res.send({
        data:{},meta:{msg:'未输入参数',status: 422}    
    })
    if(!Array.isArray(JSON.parse(detailsImg))) return res.send({
        data:{},meta:{msg:'详情图片请传入数组',status: 422}    
    })
    if(!Array.isArray(JSON.parse(discount))) return res.send({
        data:{},meta:{msg:'折扣请传入数组',status: 422}    
    })
    let  result =await goodsSer.addGoods(req.body);
    res.send({
        data:{result},meta:{msg: '添加成功',status: 201}
    })
})
//查看商品列表
goodsRouter.get('/lists',async (req,res)=>{
    let {category ,pagenum ,pagesize}=req.query;
    let result = await goodsSer.findGoods(category ,pagenum ,pagesize);
    res.send({
        data:{...result},meta:{msg: '查询成功',status: 200}
    })
})
//获取商品详细信息
goodsRouter.get('/more',async (req,res)=>{
    let {id}=req.query;
    let [result] = await goodsSer.findMore(id);
    res.send({
        data:{result},meta:{msg: '查询成功',status: 200}
    })
})
//获取所有折扣信息
goodsRouter.get('/discount',async (req,res)=>{
    let result = await goodsSer.findDiscount();
    res.send({
        data:{result},meta:{msg: '查询成功',status: 200}
    })
})
//添加新的折扣
goodsRouter.post('/addDiscount',async (req,res)=>{
    let {name,couponType,brief,couponValue}=req.body;
    if(!name ||!couponType ||!brief || ! couponValue) return res.send({
        data:{},meta:{msg:'未输入参数',status: 422}    
    })
    try {
        if(couponType==1&&!Object.prototype.toString.call(JSON.parse(couponValue))=='[object Object]') return res.send({
            data:{},meta:{msg:'折扣信息请传入对象',status: 422}    
        })
    } catch (error) {
        return res.send({
            data:{},meta:{msg:'折扣信息请传入对象',status: 422}    
        })
    }
    let result = await goodsSer.addDiscount(req.body);
    res.send({
        data:{result},meta:{msg: '添加成功',status: 201}
    })
})



module.exports=goodsRouter